﻿/****************************************************************************************************
	Copyright (C) 2010 RapidWebDev Organization (http://rapidwebdev.org)
	Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@RapidWebDev.org

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BaoJianSoft.Common;
using BaoJianSoft.Common.Caching;
using BaoJianSoft.Common.Data;
using BaoJianSoft.Common.Web;
using BaoJianSoft.Platform.Initialization;
using BaoJianSoft.Platform.Linq;

namespace BaoJianSoft.Platform.Services
{
	/// <summary>
	/// The service implementation to search accessible organizations for current authenticated user.
	/// </summary>
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
	[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
	public class OrganizationService : IOrganizationService, IRequiresSessionState
	{
		private static IPlatformConfiguration platformConfiguration = SpringContext.Current.GetObject<IPlatformConfiguration>();
		private static IMembershipApi membershipApi = SpringContext.Current.GetObject<IMembershipApi>();
		private static IOrganizationApi organizationApi = SpringContext.Current.GetObject<IOrganizationApi>();
		private static IPermissionApi permissionApi = SpringContext.Current.GetObject<IPermissionApi>();
		private static IAuthenticationContext authenticationContext = SpringContext.Current.GetObject<IAuthenticationContext>();

		/// <summary>
		/// Search organizations by a collection of criterias for the authenticated user of request.
		/// </summary>
		/// <param name="domain">Which domain of the searching organizations.</param>
		/// <param name="orgTypeId">Which organization type the searching organizations should belong to.</param>
		/// <param name="q">Keywords for searching.</param>
		/// <param name="sortDirection">Sorting field name, the default sorting field is LastUpdatedDate.</param>
		/// <param name="sortOrder">Sorting order, DESC or ASC, the default sorting order is DESC.</param>
		/// <param name="start">The start organization index of hit to return.</param>
		/// <param name="limit">The limit of returned organizations.</param>
		/// <returns>The query results object includes total hit count, returned records, start and limit.</returns>
		public QueryResultObject SearchJson(string domain, string orgTypeId, string q, string sortDirection, string sortOrder, int start, int limit)
		{
			#region Arguments Validation

			if (!authenticationContext.Identity.IsAuthenticated)
				throw new BadRequestException("The access is not authenticated.");

			Guid userId = authenticationContext.User.UserId;

			if (string.IsNullOrEmpty(domain))
				throw new BadRequestException("The parameter \"domain\" is not specified.");

			if (!platformConfiguration.Domains.Select(d => d.Value).Contains(domain))
				throw new BadRequestException("The value of parameter \"domain\" is invalid.");

			string sortOrderValue = "DESC";
			if (!Kit.IsEmpty(sortOrder))
			{
				sortOrderValue = sortOrder.ToUpperInvariant();
				if (sortOrderValue != "ASC" && sortOrderValue != "DESC")
					throw new BadRequestException("The value of parameter \"sortOrder\" is invalid. The candidate value are ASC and DESC.");
			}

			string sortFieldValue = "LastUpdatedDate";
			if (!Kit.IsEmpty(sortDirection))
				sortFieldValue = sortDirection;

			string orderby = sortFieldValue + " " + sortOrderValue;
			int pageIndex = start / limit;
			int pageSize = limit;

			Guid orgTypeIdValue = Guid.Empty;
			try
			{
				orgTypeIdValue = new Guid(orgTypeId);
			}
			catch
			{
			}

			#endregion

			QueryResultObject queryResultObject = new QueryResultObject { TotalRecordCount = 0, Start = start, Limit = limit, Records = new Collection<object>() };

			int recordCount;
			Expression<Func<Organization, bool>> predicate;
			IEnumerable<OrganizationObject> organizations;
			if (Kit.IsEmpty(q))
			{
				predicate = organization => organization.OrganizationType.Domain == domain
					&& organization.Status == OrganizationStatus.Enabled;

				if (orgTypeIdValue != Guid.Empty)
					predicate = predicate.And(org => org.OrganizationTypeId == orgTypeIdValue);

				organizations = organizationApi.FindOrganizations(predicate, null, orderby, pageIndex, pageSize, out recordCount, null);
				if (recordCount > 0)
				{
					queryResultObject.TotalRecordCount = recordCount;
					queryResultObject.Records = organizations.ToList();
				}
			}
			else
			{
				predicate = organization => organization.Status == OrganizationStatus.Enabled
					&& (organization.OrganizationCode.StartsWith(q) || organization.OrganizationName.Contains(q))
					&& organization.OrganizationType.Domain == domain;

				if (orgTypeIdValue != Guid.Empty)
					predicate = predicate.And(org => org.OrganizationTypeId == orgTypeIdValue);

				organizations = organizationApi.FindOrganizations(predicate, null, orderby, pageIndex, pageSize, out recordCount);
				if (recordCount > 0)
				{
					queryResultObject.TotalRecordCount = recordCount;
					queryResultObject.Records = organizations.ToList();
				}
			}

			return queryResultObject;
		}

		/// <summary>
		/// Get first organization matching the specified query. 
		/// The matching algorithm is to try to search organizations in following order. Once an organization is found, it's returned as the result.
		/// 1) completely match organization code;
		/// 2) completely match organization name;
		/// 3) match whether there has organizations with code starts with specified query;
		/// 4) match whether there has organizations with name starts with specified query;
		/// </summary>
		/// <param name="domain"></param>
		/// <param name="q"></param>
		/// <returns></returns>
		public OrganizationObject GetJson(string domain, string q)
		{
			if (!authenticationContext.Identity.IsAuthenticated)
				throw new BadRequestException("The access is not authenticated.");

			Guid userId = authenticationContext.User.UserId;

			if (string.IsNullOrEmpty(domain))
				throw new BadRequestException("The parameter \"domain\" is not specified.");

			if (!platformConfiguration.Domains.Select(d => d.Value).Contains(domain))
				throw new BadRequestException("The value of parameter \"domain\" is invalid.");

			int recordCount;
			IEnumerable<OrganizationTypeObject> organizationTypes = organizationApi.FindOrganizationTypes(new[] { domain });
			IEnumerable<Guid> organizationTypeIds = organizationTypes.Select(ct => ct.OrganizationTypeId);
			Expression<Func<Organization, bool>> predicate = org => org.Status == OrganizationStatus.Enabled
				&& org.OrganizationType.Domain == domain
				&& org.OrganizationCode == q;

			IEnumerable<OrganizationObject> organizations = organizationApi.FindOrganizations(predicate, null, "OrganizationCode", 0, 1, out recordCount);
			if (recordCount > 0)
				return organizations.FirstOrDefault();

			predicate = org => org.Status == OrganizationStatus.Enabled
				&& org.OrganizationType.Domain == domain
				&& org.OrganizationName == q;
			organizations = organizationApi.FindOrganizations(predicate, null, "OrganizationName", 0, 1, out recordCount);
			if (recordCount > 0)
				return organizations.FirstOrDefault();

			predicate = org => org.Status == OrganizationStatus.Enabled
				&& org.OrganizationType.Domain == domain
				&& org.OrganizationCode.StartsWith(q);
			organizations = organizationApi.FindOrganizations(predicate, null, "OrganizationCode", 0, 1, out recordCount);
			if (recordCount > 0)
				return organizations.FirstOrDefault();

			predicate = org => org.Status == OrganizationStatus.Enabled
				&& org.OrganizationType.Domain == domain
				&& org.OrganizationName.Contains(q);
			organizations = organizationApi.FindOrganizations(predicate, null, "OrganizationName", 0, 1, out recordCount);
			if (recordCount > 0)
				return organizations.FirstOrDefault();

			return null;
		}

		/// <summary>
		/// Find organization types in specified domain.
		/// </summary>
		/// <param name="domain"></param>
		/// <returns></returns>
		public QueryResultObject FindOrganizationTypesJson(string domain)
		{
			if (!authenticationContext.Identity.IsAuthenticated)
				throw new BadRequestException("The access is not authenticated.");

			if (string.IsNullOrEmpty(domain))
				throw new BadRequestException("The \"domain\" is not specified in accessing URL.");

			IEnumerable<OrganizationTypeObject> organizationTypes = organizationApi.FindOrganizationTypes(new[] { domain });
			return new QueryResultObject
			{
				Limit = int.MaxValue,
				Start = 0,
				TotalRecordCount = organizationTypes.Count(),
				Records = organizationTypes
			};
		}

		/// <summary>
		/// Lists all available organization domains.
		/// </summary>
		/// <returns></returns>
		public Collection<OrganizationDomainObject> ListDomainsJson()
		{
			IEnumerable<OrganizationDomainObject> results = platformConfiguration.Domains.Select(d => new OrganizationDomainObject { Text = d.Text, Value = d.Value });
			return new Collection<OrganizationDomainObject>(results.ToList());
		}
	}
}
